#coding:utf8
#  
# Author: TooNTonG
# Created on 2010-9-16
#
from django.http import HttpResponse
from libs.protocol import xml2PyObj 
import urllib2
import hashlib
SERVICE = '10.20.134.54'
SERVICE = 'api-filesys.wps.cn'

def _httpPost(func, data, isAssertOk = True, v = '2', http = 'HTTP'):
    url = '%s://%s/xsvr/%s/' % (http, SERVICE, func)
    xmlData = '''<?xml version="1.0"?><xLive>%s</xLive>''' %  data
    req = urllib2.Request(url, xmlData, headers = {'v':v, 'User-Agent':'toontong'})
    res = urllib2.urlopen(req, timeout = 15).read()
    #if isAssertOk:
    #    assert str(res).find('ok') != -1, (func, res, xmlData)
    return str(res)

def _call(func, token, **agr):
    data = '''<token>%s</token>''' % token
    for k, v in agr.iteritems():
        data += '''<%s>%s</%s>''' % (k, v, k)
    return _httpPost(func, data)

class Kuaipan(object):
    def __postMultipart(self, url, fields, files):
        content_type, body = self.__formatMultipart(fields, files)
        req = urllib2.Request(url, body, {'content-type':content_type, 'content-length':str(len(body))})
        return urllib2.urlopen(req).read()

    def __formatMultipart(self, fields, files, cont_type = 'application/octet-stream'):
        BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
        CRLF = '\r\n'
        L = []
        for (key, value) in fields:
            L.append('--' + BOUNDARY)
            L.append('Content-Disposition: form-data; name="%s"' % key)
            L.append('')
            L.append(value)
        for (key, filename, value) in files:
            L.append('--' + BOUNDARY)
            L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
            L.append('Content-Type: %s' % cont_type)
            L.append('')
            L.append(value)
        L.append('--' + BOUNDARY + '--')
        L.append('')
        body = CRLF.join(L)
        content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
        return content_type, body
    def _call(self, func, **agrs):
        data = ''.join([ '''<%s>%s</%s>''' % (k, v, k) for k, v in agrs.iteritems()])
        return xml2PyObj(_httpPost(func, data))
    
    def _base(self, func, token, fileId):
        agrs = {'token':token, 'fileId':fileId}
        return self._call(func, **agrs)
    
    def login(self, email, password):
        agrs = {'user':email, 'password':password, 'deviceId':'TOON', 'clientName':'TOON', 'clientVersion':'0.1'}
        self.email = email
        return self._call('login', **agrs)
    
    def dir(self, token, fileId):
        return self._base('dir', token, fileId)
    
    def _requestDown(self, token, fileId):
        res = self._base('requestDownload',token, fileId)
        assert res['result'] == 'ok', res
        return '%sstub=%s&uname=tmp.xls' % (res['xLive']['url'], res['xLive']['stub'])
    
    def down(self, token, fileId):
        '''@return: fp '''
        dwonUrl = self._requestDown(token, fileId)
        try:
            content = urllib2.urlopen(dwonUrl)
        except Exception, e:
            print e
            raise
        return content
    
    def newFolder(self, token, parentId, name):
        return self._call('newFolder', token = token, parentId = parentId, name = name)
    
    def requestUpload(self, token, fileId, fileVer, contents):
        '''@return (wssUrl, sha1)'''
        assert contents, 'can noet empty file.'
        sha1 = hashlib.sha1(contents).hexdigest()
        size = len(contents)
        res = self._call('requestUpload', token = token, sha1 = sha1, size = str(size), 
                          fileId = fileId, fileVer = str(fileVer))
        assert res['result'] == 'ok', res
        url = r"%sstub=%s&uploadSha1=%s&uploadSize=%d" % (res['xLive']['url'], res['xLive']['stub'], sha1, size)
        return url, sha1
    
    def newFile(self, token, parentId, name, contents):
        resNewFile = self._call('newFile', token = token, parentId = parentId, name = name)
        assert resNewFile['result'] in ('ok', 'targetExist'), resNewFile 
        fileId = resNewFile['xLive']['fileId']
        fileVer = resNewFile['xLive']['fileVer'] 
        upUrl, sha1 = self.requestUpload(token, fileId, fileVer, contents)
        assert upUrl, upUrl
        upRes = self.upload(upUrl, contents)
        res = {'result':'ok', 'fileId': fileId, 'sha1': sha1, 'fileVer':upRes['fileVer']}
        res.update()
        return res
        
    def upload(self, url, contents):
        respone = self.__postMultipart(url, [], [('FileCont', 'file', contents)])
        res = xml2PyObj(respone)
        assert res['wss']['result'] == 'ok', res
        return res['wss']
    
    def updateFile(self, token, fileId, fileVer, contents):
        url, sha1 = self.requestUpload(token, fileId, fileVer, contents)
        res = self.upload(url, contents)
        assert res['result'] == 'ok', res
        newFileVer = res['fileVer']
        return {'fileVer': newFileVer, 'sha1':sha1}
    
def _responseJson(pydict):
    return HttpResponse(json.dumps(pydict))
    
kuaiPanApi = Kuaipan()
  
    
import json
def login(request):
    email = request.POST.get('email')
    password = request.POST.get('password')
    res = kuaiPanApi.login(email, password)
    resp = _responseJson(res)
    if res['result'] == 'ok':
        resp.cookies['ktoken'] = res['xLive']['token']
    return resp

def fdir(request):
    def format(fileInfo):
        '''{"attr":{"id":"node_69","rel":"folder"},"data":"New node","state":"closed"}'''
        r = {}
        r['attr'] = {'id': fileInfo['fileId'], 'rel': fileInfo['type']}
        r['data'] = fileInfo['name']
        r['state'] = 'closed'
        return r
    token = request.GET.get('token')
    fileId = request.GET.get('id', '')
    if not token:
        return HttpResponse(json.dumps({}))
    result = []
    if fileId == 'root':
        result.append({'attr':{'id':'', 'rel':'root'}, 'data':'我的快盘', "state":"closed"})
        return _responseJson(result)
    kpres = kuaiPanApi.dir(token, fileId)
    if kpres['result'] != 'ok':
        return HttpResponse('{}')
    files = kpres['xLive'].get('file', [])
    for item in files:
        result.append(format(item))
    return _responseJson(result)

from libs import readxls
def down(request):
    token = request.GET.get('token')
    fileId = request.GET.get('id', '')
    content = kuaiPanApi.down(token, fileId)
    if not content:return HttpResponse(content)
    return _responseJson(readxls.read(content))
    
def dir(request):
    # token = request.GET.get('token')
    fileId = request.GET.get('id', '')
    result = []
    if fileId == 'root':
        result.append({'attr':{'id':'', 'rel':'root'}, 'data':'我的快盘', "state":"closed"})
        return _responseJson(result)
    elif fileId=='':
        res =''' [{"state": "closed", "data": "\u65b0\u5efa\u6587\u4ef6\u5939", "attr": {"id": "3289390897954817", "rel": "folder"}}, {"state": "closed", "data": "0b3c5cd1258fd0e6562c8430.jpg", "attr": {"id": "3289390897954818", "rel": "file"}}, {"state": "closed", "data": "0b3c5cd125e7d0e6562c8458.jpg", "attr": {"id": "3289390897954819", "rel": "file"}}, {"state": "closed", "data": "0c11db109ca91b34203f2e5a.jpg", "attr": {"id": "3289390897954820", "rel": "file"}}, {"state": "closed", "data": "0dd6841bf8b439e0ac6e755a.jpg", "attr": {"id": "3289390897954821", "rel": "file"}}, {"state": "closed", "data": "0ff63109291a52fa3ac76341.jpg", "attr": {"id": "3289390897954822", "rel": "file"}}, {"state": "closed", "data": "1ece4b954938203d7af48025.jpg", "attr": {"id": "3289390897954823", "rel": "file"}}, {"state": "closed", "data": "1ece4b95493f203d7af48026.jpg", "attr": {"id": "3289390897954824", "rel": "file"}}, {"state": "closed", "data": "2ca862a8e1beaf84ca130c3b.jpg", "attr": {"id": "3289390897954825", "rel": "file"}}, {"state": "closed", "data": "test.txt", "attr": {"id": "3289390897954826", "rel": "file"}}, {"state": "closed", "data": "tt.jpg", "attr": {"id": "3289390897954827", "rel": "file"}}, {"state": "closed", "data": "\u4ece\u8fd9\u91cc\u4e86\u89e3\u5feb\u76d8.rtf", "attr": {"id": "3289390897954828", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 2ca862a8e1beaf84ca130c3b.jpg", "attr": {"id": "3289390897954829", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 \u590d\u4ef6 2ca862a8e1beaf84ca130c3b.jpg", "attr": {"id": "3289390897954830", "rel": "file"}}]'''
        return HttpResponse(res)
    else:
        res = '''[{"state": "closed", "data": "0b3c5cd1258fd0e6562c8430.jpg", "attr": {"id": "3289390897954831", "rel": "file"}}, {"state": "closed", "data": "0b3c5cd125e7d0e6562c8458.jpg", "attr": {"id": "3289390897954832", "rel": "file"}}, {"state": "closed", "data": "0c11db109ca91b34203f2e5a.jpg", "attr": {"id": "3289390897954833", "rel": "file"}}, {"state": "closed", "data": "0dd6841bf8b439e0ac6e755a.jpg", "attr": {"id": "3289390897954834", "rel": "file"}}, {"state": "closed", "data": "0ff63109291a52fa3ac76341.jpg", "attr": {"id": "3289390897954835", "rel": "file"}}, {"state": "closed", "data": "1ece4b954938203d7af48025.jpg", "attr": {"id": "3289390897954836", "rel": "file"}}, {"state": "closed", "data": "1ece4b95493f203d7af48026.jpg", "attr": {"id": "3289390897954837", "rel": "file"}}, {"state": "closed", "data": "2ca862a8e1beaf84ca130c3b.jpg", "attr": {"id": "3289390897954838", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 0dd6841bf8b439e0ac6e755a.jpg", "attr": {"id": "3289390897954839", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 0ff63109291a52fa3ac76341.jpg", "attr": {"id": "3289390897954840", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 1ece4b954938203d7af48025.jpg", "attr": {"id": "3289390897954841", "rel": "file"}}, {"state": "closed", "data": "\u590d\u4ef6 2ca862a8e1beaf84ca130c3b.jpg", "attr": {"id": "3289390897954842", "rel": "file"}}] '''
        return HttpResponse(res) 
if __name__ == '__main__':
    token = kuaiPanApi.login('test110@kingsoft.com', '123456')['xLive']['token']
    print kuaiPanApi.dir(token, '')
